package com.jyw.web.controller.system;

import com.jyw.common.annotation.Anonymous;
import com.jyw.common.annotation.Log;
import com.jyw.common.constant.UserConstants;
import com.jyw.common.core.controller.BaseController;
import com.jyw.common.core.domain.AjaxResult;
import com.jyw.common.core.domain.CommonResult;
import com.jyw.common.core.domain.entity.SysDept;
import com.jyw.common.core.page.TableDataInfo;
import com.jyw.common.enums.BusinessType;
import com.jyw.common.utils.StringUtils;
import com.jyw.system.domain.SysContact;
import com.jyw.system.domain.dto.*;
import com.jyw.system.domain.vo.DeptCacheVo;
import com.jyw.system.domain.vo.SysThirdVo;
import com.jyw.system.service.ISysContactService;
import com.jyw.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门信息
 * 
 * @author system
 */
@RestController
@RequestMapping("/system/third")
@Api(tags = "第三方管理")
public class SysThirdController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;

    @Resource
    private ISysContactService contactService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    @ApiOperation("第三方列表")
    public TableDataInfo<SysDept> list(SysDept dept)
    {
        if (!ObjectUtils.isEmpty(dept)) {
            dept.setDeptType(1);
        }
        List<SysDept> depts = deptService.selectDeptList(dept);
        return getDataTable(depts);
    }


    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    @ApiOperation("第三方详情")
    public CommonResult<SysThirdVo> getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        SysDept sysDept = deptService.selectDeptById(deptId);
        List<DeptContactDto> collect = contactService.lambdaQuery()
                .eq(SysContact::getDeptId, deptId)
                .list()
                .stream()
                .map(data -> new DeptContactDto(data))
                .collect(Collectors.toList());

        SysThirdVo sysThirdVo = new SysThirdVo(sysDept, collect);

        return CommonResult.success(sysThirdVo);
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增第三方")
    public CommonResult add(@Validated @RequestBody DeptThirdAddDto addDto)
    {
        SysDept dept = addDto.buildThird();
        if (!deptService.checkDeptNameUnique(dept))
        {
            return CommonResult.error("新增第三方'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        return CommonResult.success(deptService.insertThird(addDto));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改第三方")
    public CommonResult edit(@Validated @RequestBody DeptThirdEditDto editDto)
    {
        SysDept dept = editDto.buildThird();
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept))
        {
            return CommonResult.error("修改第三方'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (!ObjectUtils.isEmpty(dept.getParentId()) &&dept.getParentId().equals(deptId))
        {
            return CommonResult.error("修改第三方'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return CommonResult.error("该第三方包含未停用的子第三方！");
        }
        return CommonResult.success(deptService.updateThird(editDto));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    @ApiOperation("删除第三方")
    public CommonResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return CommonResult.warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return CommonResult.warn("第三方存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return CommonResult.success(deptService.deleteDeptById(deptId));
    }
}
